package ru.dc.object;

import org.apache.commons.lang.StringUtils;

import java.io.Serializable;
import java.util.*;

/**
 * User: deady
 * Date: 03.11.2010
 * Time: 22:23:52
 */
public class FileInfo implements Serializable, Comparable<FileInfo> {

    private String name;
    private long length;
    private FileInfo parent;
    private boolean directory = false;
    private String tth;
    private Set<FileInfo> children = new TreeSet<FileInfo>();

    public void addChild(FileInfo file) {
        children.add(file);
        file.setParent(this);
    }

    public void removeChild(FileInfo file) {
        children.remove(file);
        file.setParent(null);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public long getLength() {
        return length;
    }

    public void setLength(long length) {
        this.length = length;
    }

    public FileInfo getParent() {
        return parent;
    }

    public void setParent(FileInfo parent) {
        this.parent = parent;
    }

    public Set<FileInfo> getChildren() {
        return Collections.unmodifiableSet(children);
    }

    public boolean isDirectory() {
        return directory;
    }

    public void setDirectory(boolean directory) {
        this.directory = directory;
    }

    public String getTth() {
        return tth;
    }

    public void setTth(String tth) {
        this.tth = tth;
    }

    @Override
    public String toString() {
        return getName();
    }

    public int compareTo(FileInfo o) {
        if (this.isDirectory() && !o.isDirectory()) {
            return -1;
        }
        else if (!this.isDirectory() && o.isDirectory()) {
            return 1;
        }
        else {
            return getName().compareToIgnoreCase(o.getName());
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        FileInfo fileInfo = (FileInfo) o;

        if (directory != fileInfo.directory) return false;
        if (length != fileInfo.length) return false;
        if (name != null ? !name.equals(fileInfo.name) : fileInfo.name != null) return false;
        if (parent != null ? !parent.equals(fileInfo.parent) : fileInfo.parent != null) return false;
        if (tth != null ? !tth.equals(fileInfo.tth) : fileInfo.tth != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + (int) (length ^ (length >>> 32));
        result = 31 * result + (parent != null ? parent.hashCode() : 0);
        result = 31 * result + (directory ? 1 : 0);
        result = 31 * result + (tth != null ? tth.hashCode() : 0);
        return result;
    }
}
